package app.itgungnir.compose.wan.widgets

import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import app.itgungnir.compose.wan.R
import coil.compose.rememberImagePainter
import coil.transform.RoundedCornersTransformation

@Composable
fun WanNetworkImage(modifier: Modifier = Modifier, width: Dp, height: Dp, url: String? = null) {
    Image(
        modifier = modifier
            .width(width)
            .height(height),
        painter = rememberImagePainter(
            data = url,
            builder = {
                placeholder(R.drawable.svg_image_placeholder)
                error(R.drawable.svg_image_error)
                transformations(RoundedCornersTransformation(15F))
            }
        ),
        contentDescription = ""
    )
}

@Composable
fun WanAvatar(modifier: Modifier = Modifier, userId: Long? = null, padding: Dp = 8.dp, onClick: (() -> Unit)? = null) {
    val avatarResourceId = when {
        userId == null -> R.drawable.svg_user_none
        userId % 10L == 0L -> R.drawable.svg_user_avatar0
        userId % 10L == 1L -> R.drawable.svg_user_avatar1
        userId % 10L == 2L -> R.drawable.svg_user_avatar2
        userId % 10L == 3L -> R.drawable.svg_user_avatar3
        userId % 10L == 4L -> R.drawable.svg_user_avatar4
        userId % 10L == 5L -> R.drawable.svg_user_avatar5
        userId % 10L == 6L -> R.drawable.svg_user_avatar6
        userId % 10L == 7L -> R.drawable.svg_user_avatar7
        userId % 10L == 8L -> R.drawable.svg_user_avatar8
        userId % 10L == 9L -> R.drawable.svg_user_avatar9
        else -> R.drawable.svg_user_none
    }
    Row(
        modifier = modifier
            .clip(CircleShape)
            .background(color = MaterialTheme.colors.background)
            .border(width = 2.dp, color = MaterialTheme.colors.secondary, shape = CircleShape)
            .then(if (onClick == null) Modifier else Modifier.clickable { onClick.invoke() }),
        verticalAlignment = Alignment.CenterVertically,
        horizontalArrangement = Arrangement.Center
    ) {
        Image(
            modifier = Modifier
                .fillMaxSize()
                .padding(all = padding),
            painter = painterResource(id = avatarResourceId),
            contentDescription = ""
        )
    }
}
